package net.sxnic.ugr.dept.util;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Set;

import net.sxnic.comm.CommConstant;
import net.sxnic.ugr.dept.Dept;
import net.sxnic.ugr.dept.DeptManager;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 
 * Comments: 部门导入工具类
 * <p>
 * Author：孙宇飞
 * <p>
 * Create Date：2010-6-8
 *  @author 吕盛槐 update date : 2011-9-26
 * 
 * 
 */
public class DeptImportUtils {

	private static Logger logger = LoggerFactory
			.getLogger(DeptImportUtils.class);

	/**
	 * 从文件导入组织机构信息 20130410开始主要使用此方法
	 * @param deptManager
	 * @param filePath
	 * @throws IOException
	 */
	public static void deptImport(DeptManager deptManager, String filePath)
			throws IOException {
		
		File file = new File(filePath);

		if (!file.exists()) {
			logger.error("file : " + filePath + " is null");
			return;
		}

		List<String> lines = FileUtils.readLines(file, "utf-8");
		
		Dept parent = null;
		Set<Dept> child = null;
		for (String line : lines) {

			if (StringUtils.isBlank(line)
					|| line.contains (CommConstant.TXT_IGNORE_CHARS)) {
				continue;
			}

			String[] m = line.split("/");

			Dept temp = deptManager.findByCode(m[0] );
			if (temp == null) {
				Dept dept = new Dept();
				//部门编码
				dept.setCode(m[0]);
				//部门名称
				dept.setName(m[1]);
				//部门全称
				dept.setFullName(m[2]);				
				//部门类别
				dept.setCtype(m[3]);
				//部门排序
				dept.setDeptOrder(Long.parseLong(m[4]));
				deptManager.save(dept);
				temp = dept;
				logger.debug("---- create dept: " + dept.getName() + " success!");
			} else {
				// 部门编码
				temp.setCode(m[0]);
				//部门名称
				temp.setName(m[1]);
				//部门全称
				temp.setFullName(m[2]);
				//部门类别
				temp.setCtype(m[3]);
				//部门排序
				temp.setDeptOrder(Long.parseLong(m[4]));
				deptManager.update(temp);

				logger.debug("---- update dept: " + temp.getName() +" success!");
			}
			
			//建立父子关系
			parent = deptManager.findByCode(m[5]);
			if(parent!=null)
			{
				//设置temp部门的父
				temp.setParent(parent);
				deptManager.update(temp);
				//设置parent的子部门
				parent.addChild(temp);
				deptManager.update(parent);
			}
		}

	}
}
